package com.affinity.impl.spi;


import java.util.BitSet;

/**
 * Simple BitSet to/from long conversion utils
 *
 * @author cheremin
 * @since 28.04.12,  14:56
 */
public final class Utils {
    private Utils() {
        throw new AssertionError( "Not for instantiation" );
    }

    public static long toLong( final BitSet bitset ) {
        if ( bitset.length() > Long.SIZE ) {
            throw new IllegalArgumentException( "Too many bits set in BitSet (" + bitset + ") to represent them as single long" );
        }

        long result = 0;
        for ( int i = 0; i < Long.SIZE; i++ ) {
            if ( bitset.get( i ) ) {
                final long mask = ( 1L << i );
                result |= mask;
            }
        }
        return result;
    }

    public static BitSet fromLong( final long bits ) {
        final BitSet result = new BitSet( Long.SIZE );

        for ( int i = 0; i < Long.SIZE; i++ ) {
            final long mask = ( 1L << i );
            if ( ( bits & mask ) != 0 ) {
                result.set( i );
            }
        }
        return result;
    }
}
